<template>
  <el-form
    :model="form"
    ref="createForm"
    :rules="rules"
    class="form mp-form"
    label-width="100px"
  >
    <el-form-item label="页面编码" prop="page_code">
      <el-input v-model="form.page_code" autocomplete="off" :disabled="isView"></el-input>
    </el-form-item>
    <el-form-item label="页面名称" prop="page_name">
      <el-input v-model="form.page_name" autocomplete="off" :disabled="isView"></el-input>
    </el-form-item>
    <el-form-item label="页面介绍" prop="page_desc">
      <el-input v-model="form.page_desc" type="textarea" :rows="2" autocomplete="off" :disabled="isView"></el-input>
    </el-form-item>
    <el-form-item label="页面类型" prop="type">
      <el-radio-group v-model="form.type" :disabled="isView">
        <el-radio-button :label="3">PC（电脑端）</el-radio-button>
        <el-radio-button :label="6">H5（手机端）</el-radio-button>
        <el-radio-button :label="7">大屏（电脑/电视）</el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="页面地址" prop="view">
      <el-input v-model="form.view" autocomplete="off" :disabled="isView" placeholder="页面地址，默认为 /apps/jwsystem/"></el-input>
    </el-form-item>
    <el-form-item label="页面路由" prop="url">
      <el-input v-model="form.url" autocomplete="off" :disabled="isView" placeholder="页面的hash地址，如：/user/list"></el-input>
    </el-form-item>

    <el-form-item label="使用接口">
      <template v-if="form.vars">
        <template v-for="(v, idx) in form.vars">
          <el-tag
            v-if="varEditIdx !== idx"
            :key="idx"
            style="display:flex;width: 100%;align-items: center;margin-bottom: 5px;"
            closable
            :disable-transitions="false"
            @close="handleRemoveVar(idx)">
            <span style="flex:1;">{{ v.type }} | {{ v.api }}</span>
            <JIcon :icon="DFT_ICONS.edit" @click="handleShowEditVar(idx)" />
          </el-tag>
        </template>
        <div v-if="varShow" style="display: flex;width:100%">
          <el-select v-model="varForm.type" style="width: 120px;margin-right: 10px;">
            <el-option value="mapi" label="微接口"></el-option>
            <el-option value="sapi" label="系统接口"></el-option>
            <el-option value="tapi" label="任务接口"></el-option>
          </el-select>
          <el-input
            v-model="varForm.api"
            autocomplete="off"
            placeholder="不同添加 /api/core 等通用前缀，以 / 开头"
            style="flex: 1;margin-right: 10px;"
          ></el-input>
          <el-button type="primary" @click="handleVarSave()">
            <template #icon>
              <JIcon :icon="DFT_ICONS.check" />
            </template>
          </el-button>
          <el-button @click="handleVarCancel()">
            <template #icon>
              <JIcon :icon="DFT_ICONS.close" />
            </template>
          </el-button>
        </div>
        <el-button v-else type="primary" plain @click="handleShowCreateVar">
          <template #icon>
            <JIcon :icon="DFT_ICONS.add" />
          </template>添加</el-button>
      </template>
    </el-form-item>

    <el-form-item v-if="isView" label-width="0" class="form-item-center">
      <el-button type="primary" @click="handleCancel()" size="default">确 定</el-button>
    </el-form-item>
    <el-form-item v-else label-width="0" class="form-item-center">
      <el-button type="primary" @click="handleSave()" size="large">确 定</el-button>
      <el-button @click="handleCancel()" size="large">取 消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import {ref, watch, onMounted} from 'vue';
import _ from 'lodash';
import {DFT_ICONS} from "@jzl/icons";

const props = defineProps({
  currentData: Object,
  appId: [String, Number],
  isView: Boolean
});

const DFT_FORM = {
  type: 3,
  page_code: '',
  page_name: '',
  page_desc: '',
  url: '',
  vars: []
};

const DFT_VAR = {
  type: "",
  api: ""
};

const loading = ref(false);
const varShow = ref(false);
const form = ref(_.cloneDeep(DFT_FORM));
const varForm = ref(_.cloneDeep(DFT_VAR));
const varFormType = ref("create");  // create | update
const varOrigForm = ref(null);
const varEditIdx = ref(null);

const rules = {
  page_code: [
    {required: true, message: '请输入页面编码', trigger: 'blur'}
  ],
  page_name: [
    {required: true, message: '请输入页面名称', trigger: 'blur'}
  ],
  type: [
    {required: true, message: '请选择页面类型', trigger: 'blur'}
  ],
  url: [
    {required: true, message: '请输入页面路径', trigger: 'blur'}
  ]
};

const init = () => {
  let formValue = null;

  if (props.currentData && props.currentData.page_id) {
    formValue = _.cloneDeep(props.currentData);
  } else {
    formValue = _.defaults({
      page_code: $utils.getNanoid(),
      app_id: props.appId
    }, DFT_FORM);
  }

  form.value = formValue;
};

const handleSave = async () => {
  loading.value = true;

  const ret = await $japi.page.pageUpsert(form.value);

  if (ret) {
    $message('操作成功！');
    emit('success', ret);
  }

  loading.value = false;
};

const handleCancel = () => {
  emit('cancel');
};

const handleShowCreateVar = () => {
  varShow.value = true;
  varForm.value = _.cloneDeep(DFT_VAR);
  varOrigForm.value = null;
  varEditIdx.value = null;
};

const handleShowEditVar = (idx) => {
  varShow.value = true;
  varOrigForm.value = form.value.vars[idx];
  varEditIdx.value = idx;
  varForm.value = _.cloneDeep(varOrigForm.value);
};

const handleRemoveVar = (idx) => {
  form.value.vars.splice(idx, 1);
  varEditIdx.value = null;
};

const handleVarSave = () => {
  if (varOrigForm.value) {
    _.assignIn(varOrigForm.value, varForm.value);
  } else {
    form.value.vars.push(varForm.value);
  }
  varShow.value = false;
  varEditIdx.value = null;
};

const handleVarCancel = () => {
  varShow.value = false;
  varEditIdx.value = null;
};

const emit = defineEmits(['success', 'cancel']);

onMounted(() => {
  init();
});

watch(() => props.currentData, () => {
  init();
}, {deep: true});
</script>
